package com.wqj.kyee.gps.bluetooth

import android.bluetooth.BluetoothAdapter
import android.bluetooth.BluetoothDevice
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.util.Log
import com.wqj.kyee.gps.bluetooth.client.BtClientThread
import com.wqj.kyee.gps.bluetooth.server.ConnectionManager
import com.wqj.kyee.gps.util.ClsUtil

/**
 * Created by kyee on 17-12-8.
 */
class BtBroadcastReceiver(activity: BtDevicesActivity): BroadcastReceiver() {
    internal var pin = "1234"
    var activity: BtDevicesActivity
    init {
        this.activity = activity
    }

     fun isRepeat( bluetoothDeviceDean:BluetoothDeviceDean ) :Boolean {
         activity.discoveredBTDevices.forEach {
             if (it.bluetoothDevice.address.equals(bluetoothDeviceDean.bluetoothDevice.address)){
                 return true
             }
         }
         return false
    }
    override fun onReceive(context: Context, intent: Intent) {

        val action = intent.action
        Log.e("action1=", action)
        var btDevice: BluetoothDevice? = null

        if (BluetoothDevice.ACTION_FOUND == action) {
            btDevice = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE)
            if (btDevice == null || btDevice!!.name == null) {
                return
            }
            Log.e("wqj", "found [" + btDevice!!.name + "]" + ":" + btDevice.address)

            if (true/*btDevice.name.contains(BTDevicesActivity.BT_DEVICE_NAME)*/) {
                var bluetoothDeviceDean = BluetoothDeviceDean(btDevice)
                var connectionManager =  ConnectionManager.getInstance();
                if(connectionManager.isConnected && btDevice==connectionManager.btd){
                    if (!isRepeat(bluetoothDeviceDean)) {
                        bluetoothDeviceDean.isContected = true;
                        activity.discoveredBTDevices.add(0, bluetoothDeviceDean)
                    }
                }else{
                    if (!isRepeat(bluetoothDeviceDean)) {
                        activity.discoveredBTDevices.add(bluetoothDeviceDean)
                    }
                }

                BtDevicesActivity.btDevicesAdapter.notifyDataSetChanged()
                Log.e("wqj", "found2 [" + btDevice!!.name + "]" + ":" + btDevice.address)

                if (btDevice.bondState == BluetoothDevice.BOND_NONE) {

                    Log.e("wqj", "attemp to bond:" + "[" + btDevice.name + "]")
                    //BTDevicesActivity.bluetoothAdapter.cancelDiscovery()
                    try {
                        //ClsUtil.createBond(btDevice.javaClass, btDevice)
                    } catch (e: Exception) {
                        // TODO Auto-generated catch block
                        e.printStackTrace()
                    }
                }
                if (!BtDevicesActivity.is_bt_connected) {
                    // 建立RFCOMM连接
                    // BTClientThread(btDevice, activity.mHandler).start()
                }

            } else {
                Log.d("wqj", "该蓝牙设备不是gps板")
            }
        } else if (action == "android.bluetooth.device.action.PAIRING_REQUEST") {
            btDevice = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE)
            if (btDevice == null) {
                return
            }
            Log.e("action2=", action)
            if (btDevice!!.name.contains(BtDevicesActivity.BT_DEVICE_NAME)) {
                Log.e("here", "OKOKOK")
                try {
                    ClsUtil.setPairingConfirmation(btDevice.javaClass, btDevice, true)
                    abortBroadcast()
                    val ret = ClsUtil.setPin(btDevice.javaClass, btDevice, pin)

                } catch (e: Exception) {
                    // TODO Auto-generated catch block
                    e.printStackTrace()
                }

            } else
                Log.e("wqj", "paring failed")

        } else if (action == BluetoothDevice.ACTION_BOND_STATE_CHANGED) {

        } else if (action == BluetoothDevice.ACTION_ACL_CONNECTED) {
            BtDevicesActivity.is_bt_connected = true
            var text = "已连接"
            //Toast.makeText(c, text, Toast.LENGTH_SHORT).show()
        } else if (action == BluetoothDevice.ACTION_ACL_DISCONNECTED) {
            BtDevicesActivity.is_bt_connected = false
            var text = "连接已断开"
            //Toast.makeText(c, text, Toast.LENGTH_SHORT).show()
        } else if (action == BluetoothAdapter.ACTION_DISCOVERY_FINISHED) {
            // MainActivity.startActivity<BTDevicesActivity>()
        }else if (action == BluetoothAdapter.ACTION_STATE_CHANGED) {
            var bluetoothAdapter = BluetoothAdapter.getDefaultAdapter()
            if(bluetoothAdapter.isEnabled){
                BtDevicesActivity.bluetoothAdapter.startDiscovery()
            }else{
                if(null != BtClientThread.btClientThread){
                    BtClientThread.btClientThread?.cancel();
                }
            }

            activity.checkBtStatus()
        }
    }
}